import type { FormInstance, FormRules, UploadFile } from "element-plus"
import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, reactive, ref } from "vue"

// 人设信息类型
export interface PersonaInfo {
  id: string
  title: string
  industry: string
  createdAt: string
  description: string
}

// 推荐模板类型
export interface RecommendTemplate {
  id: string
  name: string
  platform: string
  workflowId: string
  packages: string[]
  preview?: {
    type: "video" | "image"
    name: string
    url: string
  }
  createdAt: string
}

// 对标账号类型
export interface TargetAccount {
  id: string
  platform: string
  accountInfo: string
  analysisContent: string
  createdAt: string
}

// 模板表单类型
export interface TemplateForm {
  name: string
  platform: string
  workflowId: string
  package: string
  fileList?: UploadFile[]
}

// 对标账号表单类型
export interface TargetAccountForm {
  platform: string
  accountInfo: string
  analysisContent: string
}

export function useTemplateConfig(personaId: string) {
  // 基本状态
  const loading = ref(false)
  const personaInfo = ref<PersonaInfo | null>(null)
  const activeTab = ref<"template" | "targetAccount">("template")

  // 推荐模板相关
  const templateList = ref<RecommendTemplate[]>([])
  const showTemplateDialog = ref(false)
  const currentEditTemplate = ref<RecommendTemplate | null>(null)
  const templateFormRef = ref<FormInstance>()

  const templateForm = reactive<TemplateForm>({
    name: "",
    platform: "",
    workflowId: "",
    package: "Pro版",
    fileList: []
  })

  const templateRules: FormRules<TemplateForm> = {
    name: [
      { required: true, message: "请输入模板名称", trigger: "blur" },
      { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
    ],
    platform: [
      { required: true, message: "请选择适用平台", trigger: "change" }
    ],
    workflowId: [
      { required: true, message: "请输入工作流链路ID", trigger: "blur" },
      { max: 100, message: "长度不能超过 100 个字符", trigger: "blur" }
    ],
    package: [
      { required: true, message: "请选择套餐等级", trigger: "change" }
    ]
  }

  // 对标账号相关
  const targetAccountList = ref<TargetAccount[]>([])
  const showTargetAccountDialog = ref(false)
  const currentEditTargetAccount = ref<TargetAccount | null>(null)
  const targetAccountFormRef = ref<FormInstance>()

  const targetAccountForm = reactive<TargetAccountForm>({
    platform: "",
    accountInfo: "",
    analysisContent: ""
  })

  const targetAccountRules: FormRules<TargetAccountForm> = {
    platform: [
      { required: true, message: "请选择平台", trigger: "change" }
    ],
    accountInfo: [
      { required: true, message: "请输入对标账号信息", trigger: "blur" },
      { max: 100, message: "长度不能超过 100 个字符", trigger: "blur" }
    ],
    analysisContent: [
      { required: true, message: "请输入分析内容", trigger: "blur" },
      { min: 10, max: 500, message: "长度在 10 到 500 个字符", trigger: "blur" }
    ]
  }

  // 选项数据
  const platformOptions = [
    { label: "抖音", value: "抖音" },
    { label: "小红书", value: "小红书" },
    { label: "微信", value: "微信" },
    { label: "微博", value: "微博" }
  ]

  const packageOptions = [
    { label: "标准版", value: "标准版" },
    { label: "专业版 Pro", value: "Pro版" },
    { label: "专业版 Pro Max", value: "Pro Max版" }
  ]

  // 获取平台标签颜色
  const getPlatformTagColor = (platform: string) => {
    const colorMap: Record<string, string> = {
      抖音: "#fe2c55",
      小红书: "#ff2442",
      微信: "#07c160",
      微博: "#e6162d"
    }
    return colorMap[platform] || "#409eff"
  }

  // 获取套餐标签类型
  const getPackageTagType = (pkg: string) => {
    const typeMap: Record<string, string> = {
      "标准版": "version-standard",
      "Pro版": "version-pro",
      "Pro Max版": "version-pro-max"
    }
    return typeMap[pkg] || "version-standard"
  }

  // 获取预览图标
  const getPreviewIcon = (type?: string) => {
    return type === "video" ? "VideoPlay" : "Picture"
  }

  const getPreviewIconClass = (type?: string) => {
    return type === "video" ? "video-icon" : "image-icon"
  }

  // 标签页切换
  const handleTabChange = (tab: string | number) => {
    activeTab.value = tab as "template" | "targetAccount"
  }

  // 推荐模板相关方法
  const handleCreateTemplate = () => {
    currentEditTemplate.value = null
    resetTemplateForm()
    showTemplateDialog.value = true
  }

  const handleEditTemplate = (template: RecommendTemplate) => {
    currentEditTemplate.value = template
    // 填充表单数据
    Object.assign(templateForm, {
      name: template.name,
      platform: template.platform,
      workflowId: template.workflowId,
      package: template.packages[0] || "", // 取第一个作为单选值
      fileList: template.preview
        ? [{
            name: template.preview.name,
            url: template.preview.url
          }]
        : []
    })
    showTemplateDialog.value = true
  }

  const handleDeleteTemplate = async (template: RecommendTemplate) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除模板"${template.name}"吗？`,
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )

      // 这里调用删除API
      await deleteTemplate(template.id)

      ElMessage.success("删除成功")
    } catch (_error) {
      console.error("删除失败:", _error)
      ElMessage.error("删除失败")
    }
  }

  const handleTemplateDialogConfirm = async () => {
    if (!templateFormRef.value) return

    try {
      await templateFormRef.value.validate()
      loading.value = true

      if (currentEditTemplate.value) {
        // 编辑模式
        await updateTemplate(currentEditTemplate.value.id, templateForm)
        ElMessage.success("更新成功")
      } else {
        // 新增模式
        await createTemplate(templateForm)
        ElMessage.success("创建成功")
      }

      showTemplateDialog.value = false
    } catch (_error) {
      console.error("操作失败:", _error)
      ElMessage.error("操作失败")
    } finally {
      loading.value = false
    }
  }

  const handleTemplateDialogCancel = () => {
    showTemplateDialog.value = false
    resetTemplateForm()
  }

  const resetTemplateForm = () => {
    Object.assign(templateForm, {
      name: "",
      platform: "",
      workflowId: "",
      package: "Pro版",
      fileList: []
    })
    templateFormRef.value?.clearValidate()
  }

  // 对标账号相关方法
  const handleCreateTargetAccount = () => {
    currentEditTargetAccount.value = null
    resetTargetAccountForm()
    showTargetAccountDialog.value = true
  }

  const handleEditTargetAccount = (account: TargetAccount) => {
    currentEditTargetAccount.value = account
    // 填充表单数据
    Object.assign(targetAccountForm, {
      platform: account.platform,
      accountInfo: account.accountInfo,
      analysisContent: account.analysisContent
    })
    showTargetAccountDialog.value = true
  }

  const handleDeleteTargetAccount = async (account: TargetAccount) => {
    try {
      await ElMessageBox.confirm(
        "确定要删除这个对标账号吗？",
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )

      // 这里调用删除API
      await deleteTargetAccount(account.id)

      ElMessage.success("删除成功")
      await loadTargetAccountList()
    } catch (_error) {
      console.error("删除失败:", _error)
      ElMessage.error("删除失败")
    }
  }

  const handleTargetAccountDialogConfirm = async () => {
    if (!targetAccountFormRef.value) return

    try {
      await targetAccountFormRef.value.validate()
      loading.value = true

      if (currentEditTargetAccount.value) {
        // 编辑模式
        await updateTargetAccount(currentEditTargetAccount.value.id, targetAccountForm)
        ElMessage.success("更新成功")
      } else {
        // 新增模式
        await createTargetAccount(targetAccountForm)
        ElMessage.success("创建成功")
      }

      showTargetAccountDialog.value = false
      await loadTargetAccountList()
    } catch (_error) {
      console.error("操作失败:", _error)
      ElMessage.error("操作失败")
    } finally {
      loading.value = false
    }
  }

  const handleTargetAccountDialogCancel = () => {
    showTargetAccountDialog.value = false
    resetTargetAccountForm()
  }

  const resetTargetAccountForm = () => {
    Object.assign(targetAccountForm, {
      platform: "",
      accountInfo: "",
      analysisContent: ""
    })
    targetAccountFormRef.value?.clearValidate()
  }

  // 文件状态变更处理 - 简化版本，主要文件替换逻辑由 on-exceed 处理
  const handleFileUpload = (file: UploadFile, fileList: UploadFile[]) => {
    console.log("文件上传状态变更:", file.name, "当前列表长度:", fileList.length)
    // 由于使用了 on-exceed 进行文件替换，这里只需要记录状态变更
  }

  const handleFileRemove = () => {
    templateForm.fileList = []
  }

  // API 调用 (模拟数据)
  const loadPersonaInfo = async () => {
    try {
      loading.value = true
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300))

      personaInfo.value = {
        id: personaId,
        title: "搞笑测评员 - 模板与对标配置",
        industry: "餐饮美食",
        createdAt: "2024-02-05",
        description: "为该人设配置推荐模板和对标账号，提供精准的内容推荐"
      }
    } catch (_error) {
      console.error("加载人设信息失败:", _error)
      ElMessage.error("加载人设信息失败")
    } finally {
      loading.value = false
    }
  }

  const loadTemplateList = async () => {
    try {
      loading.value = true
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))

      templateList.value = [
        {
          id: "1",
          name: "30秒探店快剪",
          platform: "抖音",
          workflowId: "WF_QUICK_REVIEW_30S",
          packages: ["标准版", "Pro版", "Pro Max版"],
          preview: {
            type: "video",
            name: "探店快剪示例.mp4",
            url: "/preview/video1.mp4"
          },
          createdAt: "2024-08-01"
        },
        {
          id: "2",
          name: "美食种草图文",
          platform: "小红书",
          workflowId: "WF_FOOD_GRASS_POST",
          packages: ["Pro版", "Pro Max版"],
          preview: {
            type: "image",
            name: "美食种草.jpg",
            url: "/preview/image1.jpg"
          },
          createdAt: "2024-08-02"
        }
      ]
    } catch (_error) {
      console.error("获取模板列表失败:", _error)
      ElMessage.error("获取模板列表失败")
    } finally {
      loading.value = false
    }
  }

  const loadTargetAccountList = async () => {
    try {
      loading.value = true
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))

      targetAccountList.value = [
        {
          id: "1",
          platform: "抖音",
          accountInfo: "抖音号：Lilaoba_hotpot",
          analysisContent: "李老板火锅店是典型的专家型老板人设，通过专业的火锅知识分享和亲切的讲解方式，建立了强烈的信任感。其内容策略主要包括：1. 火锅食材选择技巧 2. 店铺经营心得分享 3. 与顾客的真实互动...",
          createdAt: "2024-08-01"
        }
      ]
    } catch (_error) {
      console.error("获取目标列表失败:", _error)
      ElMessage.error("获取目标列表失败")
    } finally {
      loading.value = false
    }
  }

  // API方法 (这里是模拟实现)
  const createTemplate = async (data: TemplateForm) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 处理文件上传并创建新模板
    const newTemplate: RecommendTemplate = {
      id: `template_${Date.now()}`,
      name: data.name,
      platform: data.platform,
      workflowId: data.workflowId,
      packages: [data.package],
      preview: data.fileList && data.fileList.length > 0
        ? {
            type: data.fileList[0].raw?.type?.startsWith("video") ? "video" : "image",
            name: data.fileList[0].name || "preview",
            url: data.fileList[0].url || URL.createObjectURL(data.fileList[0].raw!)
          }
        : undefined,
      createdAt: new Date().toISOString().split("T")[0]
    }

    // 添加到模板列表
    templateList.value.unshift(newTemplate)
  }

  const updateTemplate = async (id: string, data: TemplateForm) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 更新模板数据
    const templateIndex = templateList.value.findIndex(t => t.id === id)
    if (templateIndex !== -1) {
      const updatedTemplate: RecommendTemplate = {
        ...templateList.value[templateIndex],
        name: data.name,
        platform: data.platform,
        workflowId: data.workflowId,
        packages: [data.package],
        preview: data.fileList && data.fileList.length > 0
          ? {
              type: data.fileList[0].raw?.type?.startsWith("video") ? "video" : "image",
              name: data.fileList[0].name || "preview",
              url: data.fileList[0].url || URL.createObjectURL(data.fileList[0].raw!)
            }
          : templateList.value[templateIndex].preview
      }
      templateList.value[templateIndex] = updatedTemplate
    }
  }

  const deleteTemplate = async (id: string) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 从模板列表中删除
    const templateIndex = templateList.value.findIndex(t => t.id === id)
    if (templateIndex !== -1) {
      templateList.value.splice(templateIndex, 1)
    }
  }

  const createTargetAccount = async (_data: TargetAccountForm) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
  }

  const updateTargetAccount = async (_id: string, _data: TargetAccountForm) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
  }

  const deleteTargetAccount = async (_id: string) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
  }

  // 初始化数据
  onMounted(() => {
    loadPersonaInfo()
    loadTemplateList()
    loadTargetAccountList()
  })

  return {
    // 基本数据
    loading,
    personaInfo,
    activeTab,

    // 推荐模板相关
    templateList,
    showTemplateDialog,
    currentEditTemplate,
    templateForm,
    templateFormRef,
    templateRules,

    // 对标账号相关
    targetAccountList,
    showTargetAccountDialog,
    currentEditTargetAccount,
    targetAccountForm,
    targetAccountFormRef,
    targetAccountRules,

    // 方法
    handleTabChange,
    handleCreateTemplate,
    handleEditTemplate,
    handleDeleteTemplate,
    handleTemplateDialogConfirm,
    handleTemplateDialogCancel,
    handleCreateTargetAccount,
    handleEditTargetAccount,
    handleDeleteTargetAccount,
    handleTargetAccountDialogConfirm,
    handleTargetAccountDialogCancel,

    // 选项和工具方法
    platformOptions,
    packageOptions,
    getPlatformTagColor,
    getPackageTagType,
    getPreviewIcon,
    getPreviewIconClass,

    // 文件上传
    handleFileUpload,
    handleFileRemove
  }
}
